#!/bin/sh
#
# init(1) startup script for hsflowd daemon
#
# chkconfig: 345 85 15
# description: Host sFlow Daemon
# processname: hsflowd
# pidfile: /var/run/hsflowd.pid

### BEGIN INIT INFO
# Provides:          hsflowd
# Required-Start:    $syslog $network $named
# Required-Stop:     $syslog
# Default-Start:     3 4 5
# Default-Stop:      0 1 2 6
# Short-Description: Host sFlow Daemon
# Description:       Host sFlow Daemon
### END INIT INFO

. /etc/init.d/functions

HSFLOWD=/usr/sbin/hsflowd
PIDFILE=/var/run/hsflowd.pid

NAME=hsflowd
# Read configuration variable file if it is present
[ -r /etc/sysconfig/$NAME ] && . /etc/sysconfig/$NAME

# A function to test the form of a UUID string
is_uuid() {
    local UUID_REGEX;
    UUID_REGEX='^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}$'
    # newer bash supports the =~ operator but for backwards compatibility we use grep
    echo $1 | egrep $UUID_REGEX >/dev/null;
}

# A function to try and find a UUID for this host
inm_uuid() {
    local MYUUID;

    if [ -n "$UUID" ] && is_uuid "$UUID" ; then
        echo "$UUID"
        return 0
    fi

    if [ -x /usr/sbin/dmidecode ]; then
	# from the BIOS
	MYUUID=`/usr/sbin/dmidecode 2>/dev/null | awk -- '/UUID/{print $2}'`
        if is_uuid $MYUUID; then
            echo $MYUUID
	    return 0;
	fi;
    fi

    if [ -d /dev/disk/by-uuid ]; then
	# first local disk
	MYUUID=`ls /dev/disk/by-uuid | head -n 1`;
        if is_uuid $MYUUID; then
	    echo $MYUUID
	    return 0;
	fi;
    fi

    if [ -x /sbin/blkid ]; then
	# first local disk (via 'blkid')
        MYUUID=`blkid 2>/dev/null | awk -vRS=" " -vFS="=" -- '/UUID/{print $2}' | tr -d '"' | head -1`;
        if is_uuid $MYUUID; then
            echo $MYUUID
	    return 0;
	fi;
    fi

    # vol_id, tune2fs are additional options. Or a UUID can be set in the configuration file

    echo "not found";
    return 1
}

#########################################################################################
#########################################################################################

RETVAL=0

case "$1" in
       start)
	if UUID=`inm_uuid`; then
	    daemon $HSFLOWD -u "$UUID"
	else
	    daemon $HSFLOWD;
	fi
	RETVAL=$?
	;;

        stop)
	killproc hsflowd
	RETVAL=$?
        [ $RETVAL -eq 0 ] && rm -f $PIDFILE
	;;

      status)
	status hsflowd
	RETVAL=$?
	;;

     restart)
	$0 stop
	$0 start
	;;

force-reload)
	$0 stop
	$0 start
	;;
  *)
	echo "Usage: $0 {start|stop|status|restart|force-reload}"
	exit 1
esac

exit $RETVAL
